package cn.fl.system.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.multi.redis.service.IMultiRedisService;
import cmm.user.facade.system.constant.SysUsrConstant;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.base.framework.utils.VerifyCodeUtil;
import cn.fl.framework.base.constant.WebBaseConstant;
import cn.fl.system.service.ISysUsrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * @Description: 系统用户表 控制层
 */
@Controller
@RequestMapping("/system/sysUsrPwd")
public class SysUsrPwdController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SysUsrPwdController.class);

	@Autowired
	private ISysUsrService sysUsrService;

	@Resource(name = "userRedisService")
	private IMultiRedisService userRedisService;

	//1、跳转到密码重置-身份校验页面
	@RequestMapping(value = "/toVerifyIdentityPage.do", method = { RequestMethod.GET})
	public ModelAndView toVerifyIdentityPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("system/sysUsr/sysUsrPwdResetPage");
		return view;
	}



	//1、跳转到密码重置页面
	@RequestMapping(value = "/toUsrPwdResetPage.do", method = { RequestMethod.GET})
	public ModelAndView toUsrPwdResetPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("system/sysUsr/sysUsrPwdReset");
		String cacheKey = request.getParameter("cacheKey");
		String usrId = request.getParameter("usrId");
		view.addObject("cacheKey", cacheKey);
		view.addObject("usrId", usrId);
		return view;
	}

	/**
	 * 重置密码-校验身份信息
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/verifyIdentity.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object verifyIdentity(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		BaseLogUtils.info(logger, "verifyIdentity", "重置密码-校验身份信息开始");
		String usrNm = request.getParameter("usrNm");
		String verifyCd = request.getParameter("verifyCd");
		String usrMp = request.getParameter("usrMp");
		String certNo = request.getParameter("certNo");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "校验成功");
		try {
			if (StringUtils.isBlank(usrNm)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("请输入用户名称！");
				return result;
			}
			if (StringUtils.isEmpty(verifyCd)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("请输入短信验证码！");
				return result;
			}
			if (StringUtils.isEmpty(usrMp)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("请输入手机号！");
				return result;
			}
			if (StringUtils.isEmpty(certNo)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("请输入证件号码！");
				return result;
			}

			//短信发送编号
			String msgCode = SysUsrConstant.USR_CHECK_CODE+"";
			DataResultDTO resultDTO = this.sysUsrService.verifyIdentity(usrNm,msgCode,verifyCd,usrMp,certNo);
			if (null == resultDTO) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("手机验证码错误，请重新输入！");
				return result;
			} else if (BaseConstant.IS_YESNO_NO == resultDTO.getSuccess()) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(resultDTO.getInfo());
				return result;
			} else {
				result.setData(resultDTO.getData());
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "verifyIdentity", ex.getMessage(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "verifyIdentity", ex.getMessage(), ex);
		}
		BaseLogUtils.info(logger, "verifyIdentity", "重置密码-校验身份信息结束");
		return result;
	}


	/**
	 * 重置密码
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/resetPwd.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object resetPwd(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		BaseLogUtils.info(logger, "resetPwd", "重置密码处理开始");
		String newPwd = request.getParameter("newPwd");
		String surePwd = request.getParameter("surePwd");
		String cacheKey = request.getParameter("cacheKey");
		String usrId = request.getParameter("usrId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"设置密码成功，请重新登录！");
		if(StringUtils.isEmpty(cacheKey) || StringUtils.isEmpty(usrId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("重置失败，请重新进行身份校验！");
			return result;
		}
		if(StringUtils.isEmpty(newPwd) || StringUtils.isEmpty(surePwd)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新密码不能为空！");
			return result;
		}else if(!newPwd.equals(surePwd)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("两次输入密码不一致！");
			return result;
		}else if(newPwd.length() < 8 || newPwd.length() >16) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("密码长度大于等于8小于等于16！");
			return result;
		}else if(!Pattern.matches(".*[A-Z]+.*",newPwd)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("密码中必须包含大写字母！");
			return result;
		}else if(!Pattern.matches(".*[0-9]+.*",newPwd)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("密码中必须包含数字！");
			return result;
		}else if(!Pattern.matches(".*[a-z]+.*",newPwd)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("密码中必须包含小写字母！");
			return result;
		}else if(!Pattern.matches(".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*",newPwd)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("密码中必须包含特殊字符！");
			return result;
		}
		
		try {
			SysUsrDTO sysUsrDTO = (SysUsrDTO) userRedisService.get(cacheKey);
			userRedisService.delete(cacheKey);
			if(sysUsrDTO == null || !usrId.equals(String.valueOf(sysUsrDTO.getId()))){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("重置失败，请重新进行身份校验！");
				return result;
			}
			boolean success = this.sysUsrService.modifyPwdSysUsr(sysUsrDTO.getId(), newPwd, WebBaseConstant.SYS_SYS_CD, sysUsrDTO.getMp());
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("重置失败！");
				BaseLogUtils.info(logger, "resetPwd", "重置密码失败：usrId=" + usrId);
			}else {
				BaseLogUtils.info(logger, "resetPwd", "重置密码成功：usrId=" + usrId);
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "resetPwd", "重置密码失败：usrId=" + usrId + ", error:" + ex.getMessage(), ex);

		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("重置失败, 请联系管理员！");
			BaseLogUtils.error(logger, "resetPwd", "重置密码失败：usrId=" + usrId + ", error:" + ex.getMessage(), ex);
		}
		BaseLogUtils.info(logger, "resetPwd", "重置密码处理结束");
		return result;
	}



	@RequestMapping(value = "/getPhoneAuthCd.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getPhoneAuthCd(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		BaseLogUtils.info(logger, "getPhoneAuthCd", "获取短信验证码处理开始");
		String usrNm = request.getParameter("usrNm");
		String uid=request.getParameter("uid");
		String verifyImg = request.getParameter("verifyImg");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
		try {
			if (StringUtils.isBlank(usrNm)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("请输入用户名称！");
				return result;
			}
			//短信发送编号
			String msgCode = SysUsrConstant.USR_CHECK_CODE+"";

			if (StringUtils.isEmpty(verifyImg)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("请输入图片验证码！");
				return result;
			}
			Object objVerifyImg = userRedisService.get("WEBVerifyImg" + uid);
			if (null == objVerifyImg) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("图片验证码已过期，请更新后重试！");
				return result;
			}
			String strVerifyImg = objVerifyImg.toString();
			if (!verifyImg.toLowerCase().equals(strVerifyImg.toLowerCase())) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("图片验证码错误，请重新输入！");
				return result;
			}

			DataResultDTO dataResultDTO = this.sysUsrService.getAuthCdByUsrNm(usrNm, msgCode);
			if(null == dataResultDTO){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("获取短信验证码失败，请重新获取！");
			}else {
				BaseLogUtils.info(logger, "getPhoneAuthCd", "获取短信验证码结果:"+dataResultDTO.getSuccess());
				result.setSuccess(dataResultDTO.getSuccess());
				result.setInfo(dataResultDTO.getInfo());
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "getPhoneAuthCd", ex.getMessage(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "getPhoneAuthCd", ex.getMessage(), ex);
		}
		BaseLogUtils.info(logger, "getPhoneAuthCd", "获取短信验证码处理结束");
		return result;
	}

	/**
	 * @MethodName ImageCaptcha
	 * @Description: 生成随机验证码图片
	 * @Author: wangpengtao@lionbridgecapital.cn
	 * @CreateDate: 2019/2/28 9:40
	 * @Version: V1.0.0
	 * @Param request
	 * @Param response
	 * @Param model
	 * @Return void
	 * @UpdateRemark [序号][YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping(value = "/kaptcha.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object ImageCaptcha(HttpServletRequest request, HttpServletResponse response){
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");

		try {
			response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/jpeg");
			String uid = request.getParameter("uid");

			if (StringUtils.isBlank(uid)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("图片验证码生成失败，请重新获取！");
				return result;
			}

			String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
			//存入会话session
			userRedisService.setex("WEBVerifyImg"+uid,59,verifyCode.toLowerCase());
			//生成图片
			int w = 200, h = 80;
			VerifyCodeUtil.outputImage(w, h, response.getOutputStream(), verifyCode);

		} catch (IllegalArgumentException e) {
			throw new BaseException("生成验证码失败，请重试");
		} catch (IOException e) {
			throw new BaseException("生成验证码失败，请重试");
		}
		return result;
	}
}

